package com.link.play.fit.ai.ui.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
class WeightScaleView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        textSize = 32f
        textAlign = Paint.Align.CENTER
    }

    private var cellWidth = 0f
    private var minValue = 50
    private var maxValue = 200
    private var currentValue = 129
    private var isKgMode = false
    private var lastX = 0f

    fun toggleUnit() {
        isKgMode = !isKgMode
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        drawScale(canvas)
        drawCurrentValue(canvas)
    }

    private fun drawScale(canvas: Canvas) {
        val centerY = height / 2f
        val startX = width / 2f - (currentValue - minValue) * cellWidth

        // 绘制主刻度线
        for (i in minValue..maxValue step 5) {
            val x = startX + (i - minValue) * cellWidth
            val lineHeight = when {
                i % 10 == 0 -> 80f
                else -> 40f
            }
            paint.color = Color.GRAY
            canvas.drawLine(x, centerY - lineHeight, x, centerY + lineHeight, paint)

            // 绘制刻度值
            if (i % 10 == 0) {
                paint.color = Color.BLACK
                canvas.drawText(
                    if (isKgMode) "${i/2.20462.toInt()}kg" else "${i}lbs",
                    x,
                    centerY - 100f,
                    paint
                )
            }
        }
    }

    private fun drawCurrentValue(canvas: Canvas) {
        paint.color = Color.BLUE
        val displayValue = if (isKgMode)
            "%.1fkg".format(currentValue / 2.20462)
        else
            "${currentValue}lbs"

        canvas.drawText(
            "Gain Weight\n$displayValue",
            width / 2f,
            height / 4f,
            paint.apply { textSize = 48f }
        )
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> lastX = event.x
            MotionEvent.ACTION_MOVE -> {
                val dx = (event.x - lastX) / cellWidth
                currentValue = (currentValue - dx).toInt().coerceIn(minValue, maxValue)
                lastX = event.x
                invalidate()
            }
        }
        return true
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        cellWidth = w / 20f  // 每屏显示20个刻度
    }
}